package com.test30_IO流;

import org.junit.Test;

import java.io.*;

/**
 * 打印流
 * 字节打印流：PrintStream
 * 字符打印流：PrintWriter
 */
public class Demo12_PrintWriter {

    @Test
    public void test1() throws Exception {
        File file = new File("F:" + File.separator + "muyan" + File.separator + "yootk.txt");
        PrintUtil printUtil = new PrintUtil(new FileOutputStream(file));
        printUtil.print("姓名：");
        printUtil.println("李兴华");
        printUtil.println("年龄：美丽的花季少男 - 16岁");
        printUtil.close();
    }

    /**
     * 使用字符打印流输出内容
     */
    @Test
    public void test2() throws Exception {
        File file = new File("F:" + File.separator + "muyan" + File.separator + "yootk.txt");
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.print("姓名：");
        printWriter.println("李兴华");
        printWriter.println("年龄：美丽的花季少男 - 16岁");
        printWriter.close();
    }

    /**
     * 使用格式化输出操作
     */
    @Test
    public void test3() throws Exception {
        File file = new File("F:" + File.separator + "muyan" + File.separator + "yootk.txt");
        PrintWriter printWriter = new PrintWriter(file);
        String name = "李兴华";
        int age = 18;
        double score = 98.531982;
        printWriter.printf("姓名：%s、年龄：%d、成绩：%.2f", name, age, score);
        printWriter.close();
    }
}

/**
 * 个人专属的输出工具类
 */
class PrintUtil implements AutoCloseable {
    private OutputStream output;

    public PrintUtil(OutputStream output) {
        this.output = output;
    }

    public void print(String str) {
        try {
            this.output.write(str.getBytes());  // 实现字符串输出
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void println(String str) {
        this.print(str + "\r\n");
    }

    public void print(int num) {
        this.print(String.valueOf(num));
    }

    public void println(int num) {
        this.println(String.valueOf(num));
    }

    public void print(double num) {
        this.print(String.valueOf(num));
    }

    public void println(double num) {
        this.println(String.valueOf(num));
    }

    public void print(Object obj) {
        this.print(obj.toString());
    }

    public void println(Object obj) {
        this.println(obj.toString());
    }

    @Override
    public void close() throws Exception {
        this.output.close();
    }
}
